<template>
  <div id="components-form-demo-advanced-search">
    <a-form class="ant-advanced-search-form" :form="form" @submit="handleClientSubmit">
      <div class="client-header">
        <div class="client-header-title">服务单详情</div>
        <div class="client-header-copy" @click="handleCopy">复制工单</div>
        <div>
          <a-row>
            <a-col :span="24" :style="{ textAlign: 'right' }"  v-if="showClientUpdateBtn && showRoleUpdateBtn">
              <a-button class="client-update" type="primary" @click="showClientUpdate">修改</a-button>
            </a-col>
            <a-col :span="24" :style="{ textAlign: 'right' }"  v-if="!showClientUpdateBtn && showRoleUpdateBtn">
              <a-button class="client-update" type="primary" html-type="submit">确认修改</a-button>
            </a-col>
          </a-row>
        </div>
      </div>
      <div class="client-content">
        <div class="client-content-left">
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="客户姓名">
                <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['repairman',
                  {
                    initialValue: clientData.repairman,
                    rules: [{ required: true, message: '请输入合法的姓名', pattern: /^[\u4e00-\u9fa5]+$/i }]
                    },
                ]"
                         placeholder="请输入客户姓名" autoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="联系方式">
                <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['phoneNumber',
                  {
                    initialValue: clientData.phoneNumber,
                    rules: [{ required: true, message: '请输入正确的手机号', pattern: /^1[3|4|5|7|8][0-9]\d{8}$/}]
                    },
                ]"
                         placeholder="请输入联系方式" autoComplete="off" />
              </a-form-item>
              <a-form-item style="display: none">
                <a-input  v-decorator="['id',
                  { initialValue: clientData.id },
                ]" />
              </a-form-item>
              <a-form-item style="display: none">
                <a-input  v-decorator="['uploadTime',
                  { initialValue: clientData.uploadTime },
                ]" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12">
              <a-form-item label="客户单位">
                <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['companyName',
                  {
                    initialValue: clientData.companyName,
                    rules: [{ required: true, pattern: /\S/, message: '请输入客户单位' }]
                    },
                ]"
                         placeholder="请输入客户单位" autoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="机床编号">
                <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['macNumb',
                  {
                    initialValue: clientData.macNumb,
                    rules: [{ required: true, pattern: /\S/, message: '请输入机床编号' }]
                    },
                ]"
                         placeholder="请输入机床编号" autoComplete="off" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12" style="display: block">
              <a-form-item label="机床型号">
                <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['macType',
                  {
                    initialValue: clientData.macType,
                    rules: [{ required: true, pattern: /\S/, message: '请输入机床型号' }]
                    },
                ]"
                         placeholder="请输入机床型号" autoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12" style="display: block">
              <a-form-item label="系统型号">
                <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['ncSystemType',
                  {
                    initialValue: clientData.ncSystemType,
                    rules: [{ required: true, pattern: /\S/, message: '请输入系统型号' }]
                    },
                ]"
                         placeholder="请输入系统型号" autoComplete="off" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12" style="display: block">
              <a-form-item label="机床厂家">
                <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['macFactory',
                  {
                    initialValue: clientData.macFactory || '',
                    rules: [{ required: true, pattern: /\S/, message: '请输入机床厂家' }]
                    },
                ]"
                         placeholder="请输入机床厂家" autoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12" style="display: block">
              <a-form-item label="机床位置">
                <a-select :class="[showClientUpdateBtn ? 'input-disable':'']" show-search option-filter-prop="children"
                          v-decorator="['address',
          { initialValue: clientData.address || '北京市',
            rules: [{ required: true, message: '请输入机床位置' }] },
        ]"
                          placeholder="请选择案例类型"
                >
                  <a-select-option v-for="provinceItem in provinceData" :key="provinceItem" :value="provinceItem">
                    {{provinceItem}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12" style="display: block">
              <a-form-item label="设备购买时间" class="repair-form">
                <a-date-picker :class="[showClientUpdateBtn ? 'input-disable':'client-purchase-time']" v-decorator="['purchaseTime',
                  {
                    initialValue: clientData.purchaseTime || doHandleDate,
                    rules: [{ required: true, pattern: /\S/, message: '请输入设备购买时间' }]
                    },
                ]"
                               placeholder="请输入设备购买时间" autoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12" style="display: block">
              <a-form-item label="报修机床厂">
                <a-select :class="[showClientUpdateBtn ? 'input-disable':'']" show-search option-filter-prop="children"
                          v-decorator="['repairCompany',
          { initialValue: clientData.repairCompany || repairCompany[0].compName,
            rules: [{ required: true, pattern: /\S/, message: '请输入报修机床厂' }] },
        ]"
                          placeholder="请选择报修机床厂"
                >
                  <a-select-option v-for="companyItem in repairCompany" :key="companyItem.id" :value="companyItem.compName">
                    {{companyItem.compName}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24">
            <a-col :span="12" style="display: block">
              <a-form-item label="订单编号">
                <a-input class="input-disable" v-decorator="['repairOrderNumber',
                  { initialValue: clientData.repairOrderNumber },
                ]" readOnly />
              </a-form-item>
            </a-col>
            <a-col :span="12" style="display: block">
              <a-form-item label="报单人员">
                <a-input class="input-disable" v-decorator="['role',
                  { initialValue: clientData.role },
                ]" readOnly />
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <div class="client-content-right">
          <a-col :span="24" style="display: block">
            <a-form-item label="故障描述">
              <a-textarea autosize :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['description',
                  {
                    initialValue: clientData.description,
                    rules: [{ required: true, pattern: /\S/, message: '请描述故障' }]
                    },
                ]"
                       placeholder="请描述故障" autoComplete="off" />
            </a-form-item>
          </a-col>
          <a-col :span="24" style="display: block">
            <a-form-item label="用户地址">
              <a-input :class="[showClientUpdateBtn ? 'input-disable':'']" v-decorator="['fullAddress',
                  {
                    initialValue: clientData.fullAddress,
                    rules: [{ required: true, pattern: /\S/, message: '请输入用户地址' }]
                    },
                ]"
                       placeholder="请输入用户地址" autoComplete="off" />
            </a-form-item>
          </a-col>
          <div class="client-pic-title"><span class="pic-must">✻</span> 图片:</div>
          <div class="client-pic-container">
            <client-image
              :showClientUpdateBtn="showClientUpdateBtn"
              :newFileList="fileList" @handleChangePic="handleChangePic"
            ></client-image>
          </div>
        </div>
      </div>
    </a-form>
  </div>
</template>
<script>
  import ClientImage from './clientImage'
  import { mapState, mapMutations } from 'vuex'
  import api from '@/server/userConfig';
  import GLOBAL from "@/api/global_variable"
  import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
  import moment from 'moment';
  import 'moment/locale/zh-cn';
  export default {
    name: "SaleClientDetail",
    components: {
      ClientImage
    },
    props: {
      impedimentState: Number,
    },
    data () {
      return {
        expand: true,
        showClientUpdateBtn: true,
        showRoleUpdateBtn: false,
        clientData: {},
        userName: '',
        fileList: [],
        clientFileList: [],
        picturesId: '',
        originalPicturesId: '',
        form: this.$form.createForm(this, { name: 'advanced_search' }),
        provinceData: ["北京市","天津市","上海市","重庆市","河北省","山西省","内蒙古","辽宁省","吉林省","黑龙江省","江苏省","浙江省","安徽省",
          "福建省","江西省","山东省","河南省","湖北省","湖南省","广东省","广西","海南省","四川省","贵州省","云南省","西藏","陕西省","甘肃省",
          "青海省","宁夏","新疆","香港","澳门","台湾省", "研究院"],
        repairCompany: [{compId: -1, compName: '华中数控'}],
      };
    },
    computed: {
      count () {
        return this.expand ? 11 : 7;
      },
      doHandleDate: function () {
        const myDate = new Date();
        const tYear = myDate.getFullYear();
        const tMonth = myDate.getMonth();
        const tDay = myDate.getDate();
        let m = tMonth + 1;
        if (m.toString().length === 1) {
          m = "0" + m;
        }
        return moment(tYear +'-'+ m + '-' + tDay);
      }
    },
    watch: {
      impedimentState: function (newVal) {
        if (newVal !== 0) {
          this.showBillUpdate(newVal);
        }
      }
    },
    mounted () {
      this.userName = localStorage.getItem('phone');
      const { orderNumber, saleNumber, suit } = this.$route.query;
      this.getClientDetail(orderNumber);
      this.initRepairCompany();
    },
    methods: {
      showBillUpdate (impedimentState) {
        console.log(impedimentState);
        if (impedimentState === 8 || impedimentState === 9 || impedimentState === 5 ) {
          this.showRoleUpdateBtn = true
        } else {
          this.showRoleUpdateBtn = false
        }
      },
      // 复制工单;
      handleCopy () {
        console.log(this.clientData);
        // 先将数据存入缓存;
        localStorage.setItem('copyData', JSON.stringify(this.clientData));
        // 再跳转到故障报修页;
        window.open('/#/repair?id=1');
        this.handleChangeRouter('/repair');
      },
      ...mapMutations(['handleChangeRouter']),
      // 根据订单编号获取售后详情;
      async getClientDetail (orderNumber) {
        const res = await api.reqClientDetail({repairOrderNumber: orderNumber});
        if (res.MsgCode !== 0) {
          return
        }
        res.Data.purchaseTime = moment(res.Data.purchaseTime);
        this.clientData = res.Data;
        let urlArray = [];
        urlArray.push(res.Data.pictureUrl);
        let urlValue;
        //获取图片url;
        let lastUrl = [];
        for (let i = 0; i < urlArray.length; i++) {
          for (let k in urlArray[i]) {
            urlValue = urlArray[i][k];
            lastUrl.push({
              url: GLOBAL.imgDownUrl + urlArray[i][k],
              id: k
            });
          }
        }
        const fileList = lastUrl.map((item, index) => {
          return {
            uid: -index,
            name: 'image.png',
            url: item.url,
            id: item.id,
            status: 'done'
          }
        });
        let picturesId = '';
        let pictureIdArr = [];
        if (fileList.length === 0) {
          picturesId = '';
        } else {
          for (let i = 0; i < fileList.length; i++) {
            pictureIdArr.push(fileList[i].id);
            picturesId = pictureIdArr.join(',');
          }
        }
        this.originalPicturesId = picturesId;
        this.fileList = fileList;
      },
      // 获取子组件传递过来的图片;
      handleChangePic (fileList) {
        this.clientFileList = fileList;
        let picturesId = '';
        let pictureIdArr = [];
        if (fileList.length === 0) {
          picturesId = '';
        } else {
          for (let i = 0; i < fileList.length; i++) {
            pictureIdArr.push(fileList[i].id);
            picturesId = pictureIdArr.join(',');
          }
        }
        this.picturesId = picturesId;
      },
      // 确认修改服务单;
      handleClientSubmit (e) {
        e.preventDefault();
        this.form.validateFields((error, values) => {
          if (error) { return }
          console.log(values);
          let newPicturesId = '';
          // 如果没有修改图片, 则是原来的图片;
          if (this.clientFileList.length === 0) {
            if (this.fileList.length === 0) {
              this.$message.info('请至少添加一张图片');
              return;
            }
            newPicturesId = this.originalPicturesId;
          } else {
            newPicturesId = this.picturesId;
          }
          let repairNewData = {};
          repairNewData.id = values.id;
          repairNewData.repairOrderNumber = values.repairOrderNumber;
          repairNewData.description = values.description;
          repairNewData.repairman = values.repairman;   // 报修人员
          repairNewData.phoneNumber = values.phoneNumber;  // 联系电话
          repairNewData.companyName = values.companyName;  // 客户单位
          repairNewData.macNumb = values.macNumb;   // 机床编号
          repairNewData.macType = values.macType;    // 机床型号
          repairNewData.repairCompany = values.repairCompany;   // 报修机床厂
          repairNewData.state = 1;
          repairNewData.purchaseTime = values.purchaseTime;   // 设备购买时间
          repairNewData.picturesId = newPicturesId;
          repairNewData.address = values.address;   // 机床地址
          repairNewData.macFactory = values.macFactory;   // 机床厂家;
          repairNewData.ncSystemType = values.ncSystemType;   // 系统型号;
          repairNewData.fullAddress = values.fullAddress;   // 详细地址;
          repairNewData.username = this.userName;
          repairNewData.uploadTime = values.uploadTime;
          const jsonRepairNewData = JSON.stringify(repairNewData);
          //console.log(jsonRepairNewData);
          api.reqUpdateClientBill(jsonRepairNewData).then((res) => {
            if (res.MsgCode === 0) {
              this.$Modal.success({
                title: '',
                content: '修改服务单成功!',
                okText: '确定'
              });
              this.showClientUpdateBtn = true;
            } else {
              this.$message.error('修改失败...');
            }
          })
        })
      },
      handleReset () {
        this.form.resetFields();
      },
      // 初始化获取报修机床厂;
      async initRepairCompany () {
        try {
          const res = await api.reqGetRepairCompany({userName: this.userName});
          if (res.MsgCode !== 0) {
            this.$message.error('获取报修机床厂失败...');
            return;
          }
          this.repairCompany = res.Data;
        } catch (e) { console.log(e); }
      },
      // 点击服务单的修改;
      showClientUpdate (e) {
        e.preventDefault();
        this.showClientUpdateBtn = false;
      }
    }
  };
</script>
<style>
  @import "./style.css";
</style>
